package org.tuoren.official.service.impl;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.dromara.easyes.annotation.IndexName;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;
import org.tuoren.common.core.domain.R;
import org.tuoren.common.es.properties.EasyEsProperties;
import org.tuoren.common.mybatis.core.page.PageQuery;
import org.tuoren.common.mybatis.core.page.TableDataInfo;
import org.tuoren.official.domain.TNewsCenter;
import org.tuoren.official.es.domain.TNewsCenterES;
import org.tuoren.official.es.esmapper.ESNewsMapper;
import org.tuoren.official.mapper.TNewsCenterMapper;
import org.tuoren.official.service.ITNewsCenterESService;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class TNewsCenterESImpl implements ITNewsCenterESService {
    private final EasyEsProperties easyEsProperties;
    private final ESNewsMapper esNewsMapper;
    private  final TNewsCenterMapper baseMapper;

    /**
     * ES 新闻中心数据初始化
     */
    @Override
    public R<Void> initNewsES(){
        if (!easyEsProperties.getEnable()) {
            return R.fail("系统ES服务未打开！");
        }
        //1.先检查是否存在索引,存在就删除
        checkIndexExistAndRemove();
        //2.创建索引
        Boolean created = esNewsMapper.createIndex();
        if (!created) {
            return R.fail("创建ES索引失败！");
        }
        //2.构建es数据
        List<TNewsCenter> voList = baseMapper.selectList(new LambdaQueryWrapper<TNewsCenter>().eq(TNewsCenter::getIsPublish,"1"));
        List<TNewsCenterES> newsDetailEsList = voList.stream().map(blog -> {
            TNewsCenterES esBlogNews = BeanUtil.toBean(blog, TNewsCenterES.class);
            String plainTextContent = StringUtils.isEmpty(esBlogNews.getContent()) ? "" :  Jsoup.parse(esBlogNews.getContent()).text();
            esBlogNews.setContent(plainTextContent);
            Integer year = blog.getPublishDate().getYear() + 1900;
            esBlogNews.setPublishYear(year);
            Integer month = blog.getPublishDate().getMonth() + 1;
            esBlogNews.setPublishMonth(month);
            return esBlogNews;
        }).collect(Collectors.toList());
        //3.插入ES
        Integer count = esNewsMapper.insertBatch(newsDetailEsList);
        return count == newsDetailEsList.size() ? R.ok("初始化成功："+count+"条新闻"):R.fail("创建ES索引失败！");
    }

    /**
     * ES 更新/插入新闻中心
     */
    @Override
    public Boolean insertNewsES(TNewsCenter newsDetail,int type) {
        if (newsDetail.getId() == null ){
            return false;
        }
        TNewsCenterES bean = BeanUtil.toBean(newsDetail, TNewsCenterES.class);
        if (type == 1){
            return esNewsMapper.insert(bean) > 0;
        }else {
            return esNewsMapper.updateById(bean) > 0;
        }
    }

    /**
     * ES 获取新闻中心列表
     */
    @Override
    public TableDataInfo<TNewsCenterES> searchNewsES(Integer year,Integer month,String desc, PageQuery pageQuery) {
        LambdaEsQueryWrapper<TNewsCenterES> wrapper = new LambdaEsQueryWrapper<>();
        // 创建一个SimpleDateFormat对象，并指定想要的日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(desc)){
            wrapper.and(iwrapper ->wrapper.like(TNewsCenterES::getContent,desc.toLowerCase())
                .or()
                .like(TNewsCenterES::getTitle,desc.toLowerCase())
                .or()
                .like(TNewsCenterES::getNewDesc,desc.toLowerCase())
                .or()
                .like(TNewsCenterES::getSource,desc.toLowerCase()));
        }
        if(year != null && year > 0){
            wrapper.and(iwrapper -> wrapper.eq(TNewsCenterES::getPublishYear,year));
        }
        if (month != null && month > 0){
            wrapper.and(iwrapper -> wrapper.eq(TNewsCenterES::getPublishMonth,month));
        }
        wrapper.orderByDesc(TNewsCenterES::getPublishDate);
        List<TNewsCenterES> newsDetailEs = esNewsMapper.selectList(wrapper);

        Long l = esNewsMapper.selectCount(wrapper);
        System.out.println(l);
        System.out.println(JSONObject.toJSONString(newsDetailEs));
        EsPageInfo<TNewsCenterES> newsDetailEsEsPageInfo = esNewsMapper.pageQuery(wrapper, pageQuery.getPageNum(), pageQuery.getPageSize());
        List<TNewsCenterES> list= newsDetailEsEsPageInfo.getList().stream().map(item->{
            item.setPublishDateFormat(dateFormat.format(item.getPublishDate()));
            return item;
        }).collect(Collectors.toList());
        newsDetailEsEsPageInfo.setList(list);
        TableDataInfo tableDataInfo = new TableDataInfo(newsDetailEsEsPageInfo.getList(), newsDetailEsEsPageInfo.getTotal());

        tableDataInfo.setCode(HttpStatus.HTTP_OK);
        tableDataInfo.setMsg("查询成功");
        System.out.println(JSONObject.toJSONString(newsDetailEsEsPageInfo));
        return tableDataInfo;
    }

    /**
     * ES 删除新闻中心
     */
    @Override
    public Boolean deleteNewsES(Long id) {
        if (id == null || id <= 0){
            return false;
        }
        return esNewsMapper.deleteById(id) > 0;
    }

    /**
     * 查找ES中是否存在索引，存在删除该索引
     */
    private void checkIndexExistAndRemove() {
        IndexName indexName = AnnotationUtil.getAnnotation(TNewsCenterES.class, IndexName.class);
        //索引名称--如 blog_news
        String indexNameValue = indexName.value();
        Boolean existIndex = esNewsMapper.existsIndex(indexNameValue);
        if (existIndex) {
            esNewsMapper.deleteIndex(indexNameValue);
        }
    }
}
